package com.alibaba.csp.sentinel.dashboard.rule.util;

import java.util.ArrayList;
import java.util.List;

import com.sojson.config.exception.TransException;
import com.sojson.config.init.WebInit;
import com.sojson.dao.SentinelDao;
import com.sojson.entity.po.Sentinel;
import com.sojson.util.SpringUtil;
import com.sojson.util.StringUtil;
import com.sojson.util.json.JsonUtil;
import com.sojson.util.lock.CustomLock;
import com.sojson.util.lock.LockUtil;

/**
 * 规则持久化工具类
 * 
 * @author liu
 * @date 2021-09-08
 */
public class SentinelRuleUtil {

    public static SentinelDao sentinelDaoImpl = (SentinelDao)SpringUtil.getBeanByName("sentinelDaoImpl");

    /**
     * 获取规则列表
     * 
     * @param type      规则类型
     * @param appName   应用名称
     * @return
     * @throws Exception
     */
    public static <T> List<T> getRules(String type, String appName, Class<T> cla) throws Exception {
        String obj = WebInit.CACHE.getStr(type + appName);
        if (StringUtil.isBlankObject(obj)) {
            return new ArrayList<>();
        }
        return JsonUtil.jsonToList(obj, cla);
    }

    /**
     * 修改规则
     * 
     * @param type      规则类型
     * @param app       应用名称
     * @param rules     规则列表
     * @throws Exception
     */
    public static void publish(String type, String app, Object rules) throws Exception {
        int insert = 0;

        // 参数初始化
        Sentinel sentinel = new Sentinel();
        sentinel.setKey(type + app);

        // 上锁
        CustomLock lock = LockUtil.getLock(sentinel.getKey());
        lock.defaultLock();

        try {
            // 如果不存在就添加,存在就修改
            List<Integer> findIdByDto = sentinelDaoImpl.findIdByDto(sentinel);
            sentinel.setContent(JsonUtil.objectToJson(rules));
            if (findIdByDto.size() > 0) {
                sentinel.setId(findIdByDto.get(findIdByDto.size() - 1));
                insert = sentinelDaoImpl.updateById(sentinel);
            } else {
                insert = sentinelDaoImpl.insert(sentinel);
            }
        } finally {
            // 释放锁
            lock.unlock();
        }

        if (insert < 1) {
            throw new TransException("修改失败,请重试");
        }

        WebInit.CACHE.setStr(sentinel.getKey(), sentinel.getContent());
    }

}